package com.servlet;

import com.dao.user.UserDao;
import com.dao.user.UserDaoImpl;
import com.pojo.User;
import com.service.user.UserServiceImpl;
import com.util.Constant;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

public class UserChangePasswordServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String oldPassword = req.getParameter("oldPassword");
        String newPassword = req.getParameter("newPassword");
        String oldPassword1 = null;
        int flag = 0;
        String msg = "";
        /******验证旧密码*******/
        Object o = req.getSession().getAttribute(Constant.USER_SESSION);
        int userId = ((User)o).getUserId();

        UserDaoImpl userDao = new UserDaoImpl();
        try {
            oldPassword1 = userDao.oldPassword(userId);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        if(oldPassword.equals(oldPassword1)){
            UserServiceImpl userService = new UserServiceImpl();
            flag = userService.UserchangePassword(userId,newPassword);
            if(flag>0){
                req.getSession().removeAttribute(Constant.USER_SESSION);
                msg = "修改成功";
                req.setAttribute("msg",msg);
                req.getRequestDispatcher("/jsp/login.jsp").forward(req,resp);
            }else{
                System.out.println("修改失败");
                msg = "修改失败";
                req.setAttribute("msg",msg);
                req.getRequestDispatcher("/jsp/changepassword.jsp").forward(req,resp);
            }

        }else {
            System.out.println("与当前密码不匹配");
            msg = "与当前密码不匹配";
            req.setAttribute("msg",msg);
            req.getRequestDispatcher("/jsp/changepassword.jsp").forward(req,resp);
        }
        /*修改密码*/
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
